package Ip2Region

import (
	"errors"
	"strings"
)

var (
	DBFile   string
	searcher *Searcher
)

type info struct {
	IP      string
	Country string
	Region  string
	City    string
	ISP     string
}

func Search(ip string) (*info, error) {
	inf, err := search(ip)
	if err != nil {
		return nil, err
	}

	items := strings.Split(inf, "|")
	if len(items) != 5 {
		return nil, err
	}

	data := &info{}
	data.IP = ip
	data.Country = items[0]
	data.Region = items[2]
	data.City = items[3]
	data.ISP = items[4]

	return data, err
}

func SearchAddr(ip string) (string, error) {
	inf, err := Search(ip)
	if err != nil {
		return "未知地址", err
	}
	if inf == nil {
		return "未知地址", errors.New("未知地址")
	}

	addr := ""
	if inf.Country != "0" {
		addr += inf.Country
	}
	if inf.Region != "0" {
		addr += inf.Region
	}
	if inf.City != "0" {
		addr += inf.City
	}

	return addr, nil
}

func search(ip string) (string, error) {
	if DBFile == "" {
		return "", errors.New("找不到数据库文件ip2region.xdb")
	}

	if searcher == nil {
		val, err := NewSearcher(DBFile)
		if err != nil {
			return "", err
		}
		if val == nil {
			return "", errors.New("searcher初始化失败")
		}
		searcher = val
	}

	uip, err := CheckIP(ip)
	if err != nil {
		return "", err
	}

	res, _, err := searcher.Search(uip)
	return res, err
}
